package com.hopu.oa.controller.file;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GetObjectRequest;

import com.hopu.oa.dao.file.FileListDao;
import com.hopu.oa.dao.file.FilePathDao;

import com.hopu.oa.entity.file.FileList;
import com.hopu.oa.entity.file.FilePath;
import com.hopu.oa.entity.user.AoaUser;
import com.hopu.oa.service.file.FileService;
import com.hopu.oa.until.data.AliyunOSSUtil;
import com.hopu.oa.until.data.AliyunOssConfig;
import com.hopu.oa.until.data.ConstantProperties;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;


/**
 * @author Secret
 * @create 2021-07-26 下午 03:24
 */
@Controller
public class FilePathController {
    Logger log = LoggerFactory.getLogger(getClass());
    @Autowired
    private FilePathDao filePathDao;
    @Autowired
    private FileService fileService;
    @Autowired
    private FileListDao fileListDao;


    @Autowired
    private AliyunOSSUtil aliyunOSSUtil;

    @Autowired
    private ConstantProperties constantProperties;

    @RequestMapping("filemanage")
    public String filemanage(Model model, HttpSession session) {
        AoaUser user = (AoaUser) session.getAttribute("user");
        FilePath filePath = filePathDao.findByPathName(user.getUserName());
        System.out.println(filePath);

//查询之后。未找到对应用户的文件夹，则创建一个文件夹。设置parentID为1
        if (filePath == null) {
            FilePath filePath1 = new FilePath();
            filePath1.setParentId(1);
            filePath1.setPathName(user.getUserName());
            filePath1.setPathUserId(user.getUserId());
            filePathDao.insert(filePath1);
            model.addAttribute("nowpath", filePath1);
            model.addAttribute("paths", filePathDao.findPathByParentId(filePath1.getPathId()));
            model.addAttribute("files", filePathDao.findFileList(filePath1.getPathUserId()));
            model.addAttribute("userrootpath", filePath1);
            model.addAttribute("mcpaths", filePathDao.findPathByParentId(filePath1.getPathId()));
            return "file/filemanage";
        } else {
            model.addAttribute("nowpath", filePath);
            model.addAttribute("paths", filePathDao.findPathByParentId(filePath.getPathId()));
            model.addAttribute("files", filePathDao.findFileList(filePath.getPathUserId()));
            model.addAttribute("userrootpath", filePath);
            model.addAttribute("mcpaths", filePathDao.findPathByParentId(filePath.getPathId()));
            return "file/filemanage";

        }
    }

    @RequestMapping("filetest")
    public String filetest(HttpSession session,
                           @RequestParam("pathid") int pathid,
                           Model model) {
        AoaUser user = (AoaUser) session.getAttribute("user");
        FilePath userrootpath = filePathDao.findByPathName(user.getUserName());

        //查询当前目录
        FilePath filePath = filePathDao.selectById(pathid);
        // 查询当前目录的所有父级目录
        List<FilePath> allparentpaths = new ArrayList<>();
        fileService.findAllParent(filePath, allparentpaths);
        Collections.reverse(allparentpaths);
        model.addAttribute("allparentpaths", allparentpaths);
        model.addAttribute("nowpath", filePath);

        model.addAttribute("paths", fileService.findpathByparent(filePath.getPathId()));
        model.addAttribute("files", fileService.findfileBypath(filePath));
        //复制移动显示 目录
        model.addAttribute("userrootpath", userrootpath);
        model.addAttribute("mcpaths", fileService.findpathByparent(userrootpath.getPathId()));

        return "file/filemanage";
    }

    //文件上传
    @RequestMapping("fileupload")
    public String fileupload(
            int pathid,
            HttpSession session,
            @RequestParam("file") MultipartFile file,
            Model model) throws IOException {
        String fileName = file.getOriginalFilename();
        System.out.println("fileName = " + fileName);
        AoaUser user = (AoaUser) session.getAttribute("user");
        Integer userId = user.getUserId();

        FileList fileList = new FileList();
        String s = fileName.substring(fileName.lastIndexOf("-") + 1);
        String filedir = s.substring(0, s.indexOf(".") + 1);
        System.out.println("filedir = " + filedir);
        fileList.setFileName(filedir);

//        FilePath nowpath = filePathMapper.findOnePath(pathid);
        fileList.setFilePath(fileName);
        fileList.setFileName(fileName);
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        System.out.println(suffix);
        fileList.setFileShuffix(suffix);
        if (suffix.equals("jpg") || suffix.equals("png") || suffix.equals("gif") || suffix.equals("jpeg")) {
            fileList.setContentType("image");
        } else if (suffix.equals("mp4")) {
            fileList.setContentType("video");
        } else if (suffix.equals("mp3")) {
            fileList.setContentType("audio");
        } else if (suffix.equals("zip")) {
            fileList.setContentType("yasuo");
        } else {
            fileList.setContentType("file");
        }
        if (file.getSize() != 0) {

            String filename = file.getOriginalFilename();
            if (!"".equals(filename.trim())) {
                File newFile = new File(filename);
                FileOutputStream os = new FileOutputStream(newFile);
                os.write(file.getBytes());
                os.close();
                file.transferTo(newFile);
                //上传到OSS
                String uploadUrl = aliyunOSSUtil.upload(newFile);
                String url = "https://2oa-file.oss-cn-beijing.aliyuncs.com/";
                fileList.setFilePath(url + uploadUrl);
                System.out.println(url + uploadUrl);
                String FileShuffix = uploadUrl.substring(uploadUrl.lastIndexOf(".") + 1);
                fileList.setFileShuffix(FileShuffix);
            }
        }
        fileList.setPathId(pathid);
        fileList.setUploadTime(new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date()));
        fileList.setFileIsshare(0);
        fileList.setFileIstrash(0);

        fileList.setFileUserId(userId);
        fileListDao.insert(fileList);

        model.addAttribute("pathid", pathid);

        return "redirect:filemanage";
    }

    //文件下载
    @RequestMapping("downfile")
    public String downfile(@Param("fileid") int fileid,
                           Model model) {
        System.out.println("fileid = " + fileid);

        String accessKey = constantProperties.getKeyid();
        String secretKey = constantProperties.getKeysecret();
        String bucket = constantProperties.getBucketname();
        String endPoint = constantProperties.getEndpoint();

        FileList fileList = fileListDao.selectById(fileid);
        System.out.println("fileList = " + fileList);
        String fileName = fileList.getFileName();
        Integer pathId = fileList.getPathId();
        String fileUrl = fileList.getFilePath().substring(45);
        System.out.println("fileUrl = " + fileUrl);
        OSSClient client = new OSSClient(endPoint, accessKey, secretKey);

        String filePath = System.getProperty("user.dir");
        String newFilePath = filePath + "\\src\\main\\resources\\static\\image\\" + fileName;
        System.out.println("newFilePath = " + newFilePath);
        client.getObject(new GetObjectRequest(bucket, fileUrl), new File(newFilePath));

        client.shutdown();

        model.addAttribute("pathid", pathId);

        return "redirect:filemanage";
    }


    //新建文件夹
    @RequestMapping("createpath")
    public String createpath(Model model, HttpSession session,
                             @RequestParam("pathid") int pathid,
                             @RequestParam("pathname") String pathname) {
        AoaUser user = (AoaUser) session.getAttribute("user");
        FilePath filePath = filePathDao.findOnePath(pathid);
        FilePath newfilePath = new FilePath();
        newfilePath.setParentId(pathid);
        newfilePath.setPathName(pathname);
        newfilePath.setPathUserId(user.getUserId());
        filePathDao.insert(newfilePath);


        model.addAttribute("pathid", pathid);
//        return "forward:/filetest";
        return "redirect:filemanage";

    }


    //移动
    @RequestMapping("mcto")
    public String mcto(@RequestParam("morc") boolean morc,
                       @RequestParam("mctoid") Integer mctoid,
                       @RequestParam("pathid") Integer pathid,
                       @RequestParam("mcfileids") String mcfileids,
                       @RequestParam("mcpathids") String mcpathids,
                       Model model, HttpSession session) {
        System.out.println("--------------------");
        System.out.println("mcfileids" + mcfileids);
        System.out.println("mcpathids" + mcpathids);
        AoaUser user = (AoaUser) session.getAttribute("user");
        if (morc) {
            if (mcfileids != null && !"".equals(mcfileids)) {
                mcfileids = "(" + mcfileids + ")";
                fileListDao.moveFileListByBatch(mcfileids, mctoid, user.getUserId());
            }
            if (mcpathids != null && !"".equals(mcpathids)) {
                mcpathids = "(" + mcpathids + ")";
                filePathDao.moveFilePathByBatch(mcpathids, mctoid, user.getUserId());
            }
        } else {
            if (mcfileids != null && !"".equals(mcfileids)) {
                mcfileids = "(" + mcfileids + ")";
                fileListDao.moveFileListByBatch(mcfileids, mctoid, user.getUserId());
            }
        }
        model.addAttribute("pathid", pathid);
//        return "forward:/filetest";
        return "redirect:filemanage";
    }


    //分享文件
    @RequestMapping("doshare")
    public String doshare(@RequestParam("pathid") Integer pathid,
                          @RequestParam("checkfileids") List<Integer> checkfileids,
                          Model model) {
        if (!checkfileids.isEmpty()) {
            System.out.println(checkfileids);
            fileService.doshare(checkfileids);
        }
        model.addAttribute("pathid", pathid);
        model.addAttribute("message", "分享成功");
//        return "forward:/filetest";
        return "redirect:filemanage";
    }


    //删除放回收站
    @RequestMapping("deletefile")
    public String deletefile(HttpSession session,
                             @RequestParam("pathid") Integer pathid,
                             @RequestParam("checkpathids") List<Integer> checkpathids,
                             @RequestParam("checkfileids") List<Integer> checkfileids,
                             Model model) {
        AoaUser user = (AoaUser) session.getAttribute("user");
        Integer userid = user.getUserId();

        if (!checkfileids.isEmpty()) {
            // 删除文件
            //文件放入回收战
            fileService.trashfile(checkfileids, 1, userid);
        }
        if (!checkpathids.isEmpty()) {
            // 删除文件夹
            fileService.trashpath(checkpathids, 1, true);
        }
        model.addAttribute("pathid", pathid);
//        return "forward:/filetest";
        return "redirect:filemanage";
    }


    //重命名
    @RequestMapping("rename")
    public String rename(@RequestParam("name") String name,
                         @RequestParam("renamefp") Integer renamefp,
                         @RequestParam("pathid") Integer pathid,
                         @RequestParam("isfile") boolean isfile,
                         Model model) {

        //这里调用重命名方法
        fileService.rename(name, renamefp, pathid, isfile);

        model.addAttribute("pathid", pathid);
//        return "forward:/filetest";
        return "redirect:filemanage";

    }


}
